
/**  
* Project Name:zhonghecrm  
* File Name:MyExceptionHandler.java  
* Package Name:com.crm.handler  
* Date:2016年10月18日下午4:43:57   
*  
*/

package com.crm.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONObject;

/**
 * ClassName:MyExceptionHandler <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2016年10月18日 下午4:43:57 <br/>
 * 
 * @author hanlinxiu
 * @version
 * @since JDK 1.8
 * @see
 */
public class MyExceptionHandler implements HandlerExceptionResolver { 

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ex", ex);
		
		if(ex.toString().indexOf("UnknownSessionException") > -1)
			return new ModelAndView("login", map);  
		
		// 如果不是异步请求 
		if (!(request.getHeader("accept").indexOf("application/json") > -1
				|| (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {

			return new ModelAndView("error", map);

		} else {
			try {
				response.setCharacterEncoding("UTF-8");
				
				JSONObject json = new JSONObject();
				json.put("status", "error");
				json.put("msg", ex.getMessage());
				
				PrintWriter writer = response.getWriter();
				writer.print(json.toString());
				
				writer.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

	}

}
